import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Button,
  Space,
  Tag,
  Alert,
  Statistic,
  Progress,
  Divider,
  Typography,
  Tabs,
  Table,
  Tooltip,
  Badge,
  message
} from 'antd';
import {
  BulbOutlined,
  CalculatorOutlined,
  TrophyOutlined,
  BarChartOutlined,
  ThunderboltOutlined,
  RobotOutlined,
  FireOutlined,
  StarOutlined
} from '@ant-design/icons';

const { Title, Text, Paragraph } = Typography;

/**
 * 双色球预测组件
 * 提供多种预测算法分析彩票号码
 */
const LotteryPrediction = ({ historyData = [], isMobile = false }) => {
  const [predictions, setPredictions] = useState({});
  const [loading, setLoading] = useState(false);
  const [activeAlgorithm, setActiveAlgorithm] = useState('frequency');

  // 预测算法配置
  const algorithms = {
    frequency: {
      name: '频率分析',
      icon: <BarChartOutlined />,
      description: '基于历史开奖频率进行预测',
      color: '#1890ff'
    },
    trend: {
      name: '趋势分析',
      icon: <ThunderboltOutlined />,
      description: '分析号码出现趋势和周期',
      color: '#52c41a'
    },
    hot_cold: {
      name: '冷热分析',
      icon: <FireOutlined />,
      description: '基于冷热号码规律预测',
      color: '#fa541c'
    },
    pattern: {
      name: '模式识别',
      icon: <RobotOutlined />,
      description: '识别号码组合模式',
      color: '#722ed1'
    }
  };

  /**
   * 频率分析算法
   * 统计每个号码的出现频率，推荐高频号码
   */
  const frequencyAnalysis = (data) => {
    if (!data || data.length === 0) return null;

    const redFreq = {};
    const blueFreq = {};

    // 统计频率
    data.forEach(record => {
      if (record.number && record.refernumber) {
        const redNumbers = record.number.split(',').map(n => parseInt(n));
        const blueNumber = parseInt(record.refernumber);

        redNumbers.forEach(num => {
          redFreq[num] = (redFreq[num] || 0) + 1;
        });

        blueFreq[blueNumber] = (blueFreq[blueNumber] || 0) + 1;
    }
    });

    // 排序并选择推荐号码
    const sortedRed = Object.entries(redFreq)
      .sort(([,a], [,b]) => b - a)
      .slice(0, 10);
    
    const sortedBlue = Object.entries(blueFreq)
      .sort(([,a], [,b]) => b - a)
      .slice(0, 5);

    // 生成预测号码
    const predictedRed = sortedRed.slice(0, 6).map(([num]) => parseInt(num)).sort((a, b) => a - b);
    const predictedBlue = parseInt(sortedBlue[0][0]);

    return {
      redNumbers: predictedRed,
      blueNumber: predictedBlue,
      confidence: Math.min(95, 60 + (data.length / 10)),
      analysis: {
        redFrequency: sortedRed,
        blueFrequency: sortedBlue,
        totalRecords: data.length
      }
    };
  };

  /**
   * 趋势分析算法
   * 分析最近期号码的出现趋势
   */
  const trendAnalysis = (data) => {
    if (!data || data.length < 10) return null;

    const recentData = data.slice(-20); // 最近20期
    const redTrend = {};
    const blueTrend = {};

    // 计算趋势权重（越近期权重越高）
    recentData.forEach((record, index) => {
      const weight = index + 1; // 权重递增
      
      if (record.number && record.refernumber) {
        const redNumbers = record.number.split(',').map(n => parseInt(n));
        const blueNumber = parseInt(record.refernumber);

        redNumbers.forEach(num => {
          redTrend[num] = (redTrend[num] || 0) + weight;
        });

        blueTrend[blueNumber] = (blueTrend[blueNumber] || 0) + weight;
      }
    });

    // 排序并选择推荐号码
    const sortedRed = Object.entries(redTrend)
      .sort(([,a], [,b]) => b - a)
      .slice(0, 8);
    
    const sortedBlue = Object.entries(blueTrend)
      .sort(([,a], [,b]) => b - a)
      .slice(0, 3);

    const predictedRed = sortedRed.slice(0, 6).map(([num]) => parseInt(num)).sort((a, b) => a - b);
    const predictedBlue = parseInt(sortedBlue[0][0]);

    return {
      redNumbers: predictedRed,
      blueNumber: predictedBlue,
      confidence: Math.min(90, 50 + (recentData.length * 2)),
      analysis: {
        recentTrend: sortedRed,
        blueTrend: sortedBlue,
        analyzedPeriods: recentData.length
      }
    };
  };

  /**
   * 冷热分析算法
   * 基于号码的冷热状态进行预测
   */
  const hotColdAnalysis = (data) => {
    if (!data || data.length < 15) return null;

    const recentPeriods = 10;
    const recentData = data.slice(-recentPeriods);
    const allData = data;

    const recentRed = new Set();
    const recentBlue = new Set();
    const allRed = {};
    const allBlue = {};

    // 统计最近期出现的号码（热号）
    recentData.forEach(record => {
      if (record.number && record.refernumber) {
        const redNumbers = record.number.split(',').map(n => parseInt(n));
        const blueNumber = parseInt(record.refernumber);

        redNumbers.forEach(num => recentRed.add(num));
        recentBlue.add(blueNumber);
      }
    });

    // 统计所有期号码频率
    allData.forEach(record => {
      if (record.number && record.refernumber) {
        const redNumbers = record.number.split(',').map(n => parseInt(n));
        const blueNumber = parseInt(record.refernumber);

        redNumbers.forEach(num => {
          allRed[num] = (allRed[num] || 0) + 1;
        });
        allBlue[blueNumber] = (allBlue[blueNumber] || 0) + 1;
      }
    });

    // 找出冷号（频率高但最近未出现）
    const coldRed = Object.entries(allRed)
      .filter(([num]) => !recentRed.has(parseInt(num)))
      .sort(([,a], [,b]) => b - a)
      .slice(0, 10);

    const coldBlue = Object.entries(allBlue)
      .filter(([num]) => !recentBlue.has(parseInt(num)))
      .sort(([,a], [,b]) => b - a)
      .slice(0, 5);

    // 组合冷热号码
    const hotRed = Array.from(recentRed).slice(0, 3);
    const coldRedNums = coldRed.slice(0, 3).map(([num]) => parseInt(num));
    const predictedRed = [...hotRed, ...coldRedNums].sort((a, b) => a - b);
    
    const predictedBlue = coldBlue.length > 0 ? parseInt(coldBlue[0][0]) : Array.from(recentBlue)[0];

    return {
      redNumbers: predictedRed,
      blueNumber: predictedBlue,
      confidence: Math.min(85, 45 + (data.length / 5)),
      analysis: {
        hotNumbers: Array.from(recentRed),
        coldNumbers: coldRed.map(([num]) => parseInt(num)),
        recentPeriods
      }
    };
  };

  /**
   * 模式识别算法
   * 识别号码组合的规律和模式
   */
  const patternRecognition = (data) => {
    if (!data || data.length < 20) return null;

    const patterns = {
      consecutive: 0, // 连号
      evenOdd: { even: 0, odd: 0 }, // 奇偶比
      sumRange: {}, // 和值范围
      span: {} // 跨度
    };

    data.forEach(record => {
      if (record.number) {
        const numbers = record.number.split(',').map(n => parseInt(n)).sort((a, b) => a - b);
        
        // 分析连号
        let consecutive = 0;
        for (let i = 0; i < numbers.length - 1; i++) {
          if (numbers[i + 1] - numbers[i] === 1) consecutive++;
        }
        patterns.consecutive += consecutive;

        // 分析奇偶比
        const evenCount = numbers.filter(n => n % 2 === 0).length;
        const oddCount = numbers.length - evenCount;
        patterns.evenOdd.even += evenCount;
        patterns.evenOdd.odd += oddCount;

        // 分析和值
        const sum = numbers.reduce((a, b) => a + b, 0);
        const sumRange = Math.floor(sum / 10) * 10;
        patterns.sumRange[sumRange] = (patterns.sumRange[sumRange] || 0) + 1;

        // 分析跨度
        const span = numbers[numbers.length - 1] - numbers[0];
        patterns.span[span] = (patterns.span[span] || 0) + 1;
      }
    });

    // 基于模式生成预测
    const avgConsecutive = patterns.consecutive / data.length;
    const evenOddRatio = patterns.evenOdd.even / (patterns.evenOdd.even + patterns.evenOdd.odd);
    
    const mostCommonSum = Object.entries(patterns.sumRange)
      .sort(([,a], [,b]) => b - a)[0];
    
    const mostCommonSpan = Object.entries(patterns.span)
      .sort(([,a], [,b]) => b - a)[0];

    // 生成符合模式的号码组合
    const predictedRed = generatePatternNumbers(evenOddRatio, parseInt(mostCommonSum[0]), parseInt(mostCommonSpan[0]));
    const predictedBlue = Math.floor(Math.random() * 16) + 1; // 蓝球随机生成

    return {
      redNumbers: predictedRed,
      blueNumber: predictedBlue,
      confidence: Math.min(80, 40 + (data.length / 8)),
      analysis: {
        avgConsecutive: avgConsecutive.toFixed(2),
        evenOddRatio: (evenOddRatio * 100).toFixed(1) + '%',
        commonSumRange: mostCommonSum[0],
        commonSpan: mostCommonSpan[0]
      }
    };
  };

  /**
   * 根据模式生成号码
   */
  const generatePatternNumbers = (evenOddRatio, targetSum, targetSpan) => {
    const numbers = [];
    const evenCount = Math.round(6 * evenOddRatio);
    const oddCount = 6 - evenCount;

    // 生成基础号码
    let attempts = 0;
    while (numbers.length < 6 && attempts < 100) {
      const num = Math.floor(Math.random() * 33) + 1;
      if (!numbers.includes(num)) {
        const currentEven = numbers.filter(n => n % 2 === 0).length;
        const currentOdd = numbers.filter(n => n % 2 === 1).length;
        
        if ((num % 2 === 0 && currentEven < evenCount) || 
            (num % 2 === 1 && currentOdd < oddCount)) {
          numbers.push(num);
        }
      }
      attempts++;
    }

    // 补充到6个号码
    while (numbers.length < 6) {
      const num = Math.floor(Math.random() * 33) + 1;
      if (!numbers.includes(num)) {
        numbers.push(num);
      }
    }

    return numbers.sort((a, b) => a - b);
  };

  /**
   * 执行预测算法
   */
  const runPrediction = async (algorithm) => {
    // 检查算法是否存在
    if (!algorithms[algorithm]) {
      message.error('未知的预测算法');
      return;
    }
    
    setLoading(true);
    
    try {
      await new Promise(resolve => setTimeout(resolve, 1000)); // 模拟计算时间
      
      let result = null;
      
      switch (algorithm) {
        case 'frequency':
          result = frequencyAnalysis(historyData);
          break;
        case 'trend':
          result = trendAnalysis(historyData);
          break;
        case 'hot_cold':
          result = hotColdAnalysis(historyData);
          break;
        case 'pattern':
          result = patternRecognition(historyData);
          break;
        default:
          result = frequencyAnalysis(historyData);
      }

      if (result) {
        setPredictions(prev => ({
          ...prev,
          [algorithm]: result
        }));
        message.success(`${algorithms[algorithm].name}预测完成！`);
      } else {
        message.warning('数据不足，无法进行预测');
      }
    } catch (error) {
      message.error('预测计算失败');
    } finally {
      setLoading(false);
    }
  };

  /**
   * 渲染号码球
   */
  const renderNumberBalls = (numbers, type = 'red') => {
    const ballStyle = {
      red: {
        backgroundColor: '#ff4d4f',
        color: 'white',
        border: '2px solid #ff7875'
      },
      blue: {
        backgroundColor: '#1890ff',
        color: 'white',
        border: '2px solid #40a9ff'
      }
    };

    return (
      <Space wrap>
        {(Array.isArray(numbers) ? numbers : [numbers]).map((num, index) => (
          <div
            key={index}
            style={{
              ...ballStyle[type],
              width: isMobile ? 28 : 32,
              height: isMobile ? 28 : 32,
              borderRadius: '50%',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: isMobile ? '12px' : '14px',
              fontWeight: 'bold',
              margin: '2px'
            }}
          >
            {String(num).padStart(2, '0')}
          </div>
        ))}
      </Space>
    );
  };

  /**
   * 渲染预测结果
   */
  const renderPredictionResult = (algorithm) => {
    const prediction = predictions[algorithm];
    if (!prediction || !algorithms[algorithm]) return null;

    return (
      <Card
        size="small"
        style={{ marginTop: 16 }}
        title={
          <Space>
            {algorithms[algorithm].icon}
            <span>{algorithms[algorithm].name}预测结果</span>
            <Badge 
              count={`${prediction.confidence.toFixed(0)}%`} 
              style={{ backgroundColor: algorithms[algorithm].color }}
            />
          </Space>
        }
      >
        <Row gutter={[16, 16]}>
          <Col span={24}>
            <div style={{ textAlign: 'center', padding: '16px 0' }}>
              <Title level={5} style={{ marginBottom: 16 }}>推荐号码组合</Title>
              <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                <div>
                  <Text strong>红球：</Text>
                  {renderNumberBalls(prediction.redNumbers, 'red')}
                </div>
                <div>
                  <Text strong>蓝球：</Text>
                  {renderNumberBalls([prediction.blueNumber], 'blue')}
                </div>
              </Space>
            </div>
          </Col>
        </Row>
        
        <Divider />
        
        <Row gutter={[16, 8]}>
          <Col span={isMobile ? 24 : 8}>
            <Statistic
              title="预测可信度"
              value={prediction.confidence}
              precision={1}
              suffix="%"
              valueStyle={{ color: algorithms[algorithm].color }}
            />
          </Col>
          <Col span={isMobile ? 24 : 8}>
            <Statistic
              title="分析样本"
              value={historyData.length}
              suffix="期"
            />
          </Col>
          <Col span={isMobile ? 24 : 8}>
            <Statistic
              title="算法类型"
              value={algorithms[algorithm].name}
              valueStyle={{ fontSize: '14px' }}
            />
          </Col>
        </Row>
      </Card>
    );
  };

  // 初始加载时运行频率分析
  useEffect(() => {
    if (historyData && historyData.length > 0) {
      runPrediction('frequency');
    }
  }, [historyData]);

  return (
    <div style={{ padding: isMobile ? '8px' : '16px' }}>
      {/* 预测说明 */}
      <Alert
        message="智能预测说明"
        description={
          <div>
            <Paragraph style={{ marginBottom: 8 }}>
              本预测功能基于历史开奖数据，使用多种数学算法进行分析。预测结果仅供参考，不构成投注建议。
            </Paragraph>
            <ul style={{ marginLeft: 20, marginBottom: 0 }}>
              <li>频率分析：统计号码出现频率，推荐高频号码</li>
              <li>趋势分析：分析近期号码趋势，预测延续性</li>
              <li>冷热分析：结合冷热号码规律进行预测</li>
              <li>模式识别：识别号码组合的数学模式</li>
            </ul>
          </div>
        }
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
      />

      {/* 算法选择 */}
      <Card title={
        <Space>
          <BulbOutlined />
          <span>选择预测算法</span>
        </Space>
      }>


        <Row gutter={[16, 16]}>
          {Object.entries(algorithms).map(([key, algo]) => (
            <Col key={key} span={isMobile ? 12 : 6}>
              <Card
                size="small"
                hoverable
                style={{
                  border: activeAlgorithm === key ? `2px solid ${algo.color}` : '1px solid #d9d9d9',
                  cursor: 'pointer'
                }}
                onClick={() => setActiveAlgorithm(key)}
              >
                <div style={{ textAlign: 'center' }}>
                  <div style={{ fontSize: 24, color: algo.color, marginBottom: 8 }}>
                    {algo.icon}
                  </div>
                  <Title level={5} style={{ margin: 0, fontSize: isMobile ? 12 : 14 }}>
                    {algo.name}
                  </Title>
                  <Text type="secondary" style={{ fontSize: isMobile ? 10 : 12 }}>
                    {algo.description}
                  </Text>
                </div>
              </Card>
            </Col>
          ))}
        </Row>

        <div style={{ textAlign: 'center', marginTop: 16 }}>
          <Button
            type="primary"
            size="large"
            icon={<CalculatorOutlined />}
            loading={loading}
            onClick={() => runPrediction(activeAlgorithm)}
            disabled={historyData.length === 0}
          >
            {loading ? '正在预测...' : '开始预测'}
          </Button>
        </div>

        {/* 预测结果 */}
        {renderPredictionResult(activeAlgorithm)}
      </Card>

      {/* 历史预测记录 */}
      {Object.keys(predictions).length > 1 && (
        <Card
          title={
            <Space>
              <StarOutlined />
              <span>预测历史</span>
            </Space>
          }
          style={{ marginTop: 16 }}
        >
          <Tabs
            size={isMobile ? 'small' : 'default'}
            items={Object.entries(predictions)
              .filter(([key]) => algorithms[key]) // 过滤掉不存在的算法
              .map(([key, prediction]) => ({
                key,
                label: algorithms[key].name,
                children: renderPredictionResult(key)
              }))}
          />
        </Card>
      )}

      {/* 数据不足提示 */}
      {historyData.length === 0 && (
        <Card style={{ textAlign: 'center', marginTop: 16 }}>
          <div style={{ padding: '40px 0' }}>
            <BulbOutlined style={{ fontSize: 48, color: '#d9d9d9' }} />
            <div style={{ marginTop: 16, color: '#999' }}>
              暂无历史数据，无法进行预测
            </div>
            <Text type="secondary">
              请先同步历史开奖数据
            </Text>
          </div>
        </Card>
      )}
    </div>
  );
};

export default LotteryPrediction;